<?php

namespace App\Http\Controllers;

use App\Models\UsersModel;
use Illuminate\Support\Facades\Hash;
use Lib\Util\JWT;

class LoginController extends Controller
{
    protected $check_login = false;

    /**
     * 登陆
     * @return bool
     */
    public function login()
    {
        $mobile = $this->request->input('mobile');
        $password = $this->request->input('password');

        $user = UsersModel::query()->where(['mobile' => $mobile])->first();

        if (empty($user)) {
            return $this->fail(CODE_ERR_AUTH_USERNAME);
        }

        if (!Hash::check($password, $user->password)) {
            return $this->fail(CODE_ERR_AUTH_PASSWORD);
        }

        $data = [
            'iat' => time(),
            'exp' => strtotime('+1 day'),
            'user_info' => [
                'id' => $user->id,
                'username' => $user->username,
                'email' => $user->avatar,
                'avatar' => $user->avatar,
                'mobile' => cover_mobile($user->mobile),
                'sign' => $user->sign,
                'is_vip' => $user->is_vip,
                'vip_end_time' => $user->vip_end_time,
                'is_meeting' => (bool)$user->is_meeting
            ]
        ];

        $token = JWT::token($data);

        return $this->success([
            'id' => $user->id,
            'mobile' => $user->mobile,
            'username' => $user->username,
            'avatar' => $user->avatar,
            'token' => $token,
        ]);
    }

    public function register()
    {
        $mobile = $this->request->input('mobile');
        $verify_code = $this->request->input('verify_code');
        $password = $this->request->input('password');

        $usersModel = UsersModel::query();

        // 验证验证码
        $user = $usersModel->where(['mobile' => $mobile])->first();
        if ($user) {
            return $this->fail(CODE_ERR_PARAM, '手机号已存在');
        }

        $res = $usersModel->insert([
            'mobile' => $mobile,
            'password' => Hash::make($password),
        ]);

        if (!$res) {
            return $this->fail(CODE_ERR_SYSTEM, '注册失败，请重试！');
        }

        return $this->success([], '注册成功');
    }

    public function logout()
    {

    }
}
